package com.troila.cloud.simplify.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.troila.cloud.simplify.AttachmentSettings;
import com.troila.cloud.simplify.utils.IdUtil;

import net.coobird.thumbnailator.Thumbnails;

@Service
@EnableConfigurationProperties(AttachmentSettings.class)
public class FileService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);

	@Autowired
	private AttachmentSettings settings;

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public String uploadFile(HttpSession session,MultipartFile file) {
		
		FileInfo info = getFileInfo(file);
		String path = "";
		try {
			writeInternal(session, info);
			path = settings.getRootFolder() + "/" + info.getTmpName();
			
		} catch(Exception e) {
			new File(settings.getRootFolder() + "/" + info.getTmpName()).delete();
			LOGGER.error("文件【{}】上传异常：{}", file.getOriginalFilename(), e.getMessage(), e);
			
		}
		
		return info.getTmpName();
	}

	private FileInfo getFileInfo(MultipartFile file) {

		FileInfo info = new FileInfo();
		info.setFileName(file.getOriginalFilename());
		info.setSize(file.getSize());
		String extension = info.getFileName().substring(info.getFileName().lastIndexOf('.') + 1);
		info.setExtension(extension);
		info.setMime(settings.getMimeByExtension(extension, "application/octet-stream"));
		info.setFile(file);
		info.setTmpName(IdUtil.getUuid() + "." + extension);
		info.setId(info.getTmpName());

		return info;
	}

	private void writeInternal(HttpSession session, FileInfo file) throws Exception {

		if(!file.getFile().isEmpty()) {
			File f = new File(settings.getRootFolder());
			if(!f.exists()) {
				f.createNewFile();
			}
		       Thumbnails.of(file.getFile().getInputStream()) 
		       .scale(1f) 
		       .outputQuality(0.5f) 
		       .toFile(settings.getRootFolder() + "/" + file.getTmpName());
			/*BufferedOutputStream os = new BufferedOutputStream(
					new FileOutputStream(settings.getRootFolder() + "/" + file.getTmpName()));
			InputStream is = file.getFile().getInputStream();
			try {
				byte[] buffer = new byte[4096];
				int nread = 0;
				int totalRead = 0;
				while((nread = is.read(buffer)) > 0) {
					os.write(buffer);
					totalRead += nread;
					int progress = (int) (100 * ((float) totalRead / file.getSize()));
					session.setAttribute(file.getId(), progress);
				}
				os.flush();
			} finally {
				session.removeAttribute(file.getId());
				os.close();
				is.close();
			}*/
		}
	}



	class FileInfo {

		private String id;

		private String fileName;

		private String extension;

		private String mime;

		private long size;

		private String tmpName;

		private MultipartFile file;

		private InputStream stream;

		public String getId() {

			return id;
		}

		public void setId(String id) {

			this.id = id;
		}

		public String getFileName() {

			return fileName;
		}

		public void setFileName(String fileName) {

			this.fileName = fileName;
		}

		public String getExtension() {

			return extension;
		}

		public void setExtension(String extension) {

			this.extension = extension;
		}

		public String getMime() {

			return mime;
		}

		public void setMime(String mime) {

			this.mime = mime;
		}

		public long getSize() {

			return size;
		}

		public void setSize(long size) {

			this.size = size;
		}

		public String getTmpName() {

			return tmpName;
		}

		public void setTmpName(String tmpName) {

			this.tmpName = tmpName;
		}

		public MultipartFile getFile() {

			return file;
		}

		public void setFile(MultipartFile file) {

			this.file = file;
		}

		public InputStream getStream() {

			return stream;
		}

		public void setStream(InputStream stream) {

			this.stream = stream;
		}
	}
	
	public static void main(String[] args) throws IOException {
	       Thumbnails.of("C:\\Users\\wangxuewei\\Downloads\\aaa.png") 
	       .scale(1f) 
	       .outputQuality(0.5f) 
	       .toFile("C:\\Users\\wangxuewei\\Downloads\\aaa.jpg");
	}
}